﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Asset
{
    public class AsyncBundle : Bundle
    {
        protected AssetBundleCreateRequest request;
        public AsyncBundle(string url) : base(url)
        {

        }

        protected override void initialize()
        {
            string[] deps = PoolMgr.getDeps(this.URL);
            if (deps != null)
            {
                depends = new List<IAsyncBundle>();
                for (int i = 0; i < deps.Length; i++)
                {
                    IAsyncBundle depBundle = ResPool.Instance.getBundle(deps[i]);
                    if (depBundle == null)
                    {
                        depBundle = new AsyncBundle(deps[i]);
                        ResPool.Instance.addBundle(depBundle);
                    }
                    depends.Add(depBundle);
                }
            }
        }

        public override IEnumerator doLoad()
        {
            if (this.Status == AsyncStatus.Waiting)
            {
                this.asyncStatus = AsyncStatus.Running;
                request = AssetBundle.LoadFromFileAsync(this.resPath);
                yield return request;
            }
            else if (this.Status == AsyncStatus.Running)
            {
                if (this.request.isDone)
                {
                    this.asyncStatus = AsyncStatus.Finish;
#if UNITY_EDITOR
                    this.costTimeMillSec = (int)(TimeUtils.nowTime - initTime);
#endif
                    this.assetBundle = request.assetBundle;
                }
            }
        }

        //异步bundle 被同步调用
        public override T loadAsset<T>(string resName)
        {
            if (this.Status != AsyncStatus.Finish)
            {
                if (this.depends != null)
                {
                    for (int i = 0; i < this.depends.Count; i++)
                    {
                        this.depends[i].doLoadImm();
                    }
                }
            }
            this.doLoadImm();
            Asset<T> asset = new Asset<T>(resName, this);
            return asset.Result;
        }

    }

}
